package com.wenx.v3gateway.config;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * 熔断器配置类
 * 提供简化的默认熔断器配置
 */
@Configuration
@ConditionalOnProperty(name = "cloud.gateway.circuit-breaker.enabled", havingValue = "true", matchIfMissing = true)
public class CircuitBreakerConfig {

    /**
     * 默认熔断器配置
     */
    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> {
            // 配置默认熔断器 - 适用于所有服务的通用配置
            factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                    .circuitBreakerConfig(io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.custom()
                            .slidingWindowType(SlidingWindowType.COUNT_BASED)  // 基于请求数量的滑动窗口
                            .slidingWindowSize(10)                             // 滑动窗口大小：10个请求
                            .minimumNumberOfCalls(5)                           // 最小调用次数：5次
                            .failureRateThreshold(50.0f)                       // 失败率阈值：50%
                            .slowCallRateThreshold(100.0f)                     // 慢调用率阈值：100%（禁用慢调用检测）
                            .slowCallDurationThreshold(Duration.ofSeconds(60)) // 慢调用时间阈值：60秒
                            .waitDurationInOpenState(Duration.ofSeconds(30))   // 熔断器开启状态等待时间：30秒
                            .permittedNumberOfCallsInHalfOpenState(3)          // 半开状态允许的调用次数：3次
                            .automaticTransitionFromOpenToHalfOpenEnabled(true) // 自动从开启状态转换为半开状态
                            .build())
                    .timeLimiterConfig(TimeLimiterConfig.custom()
                            .timeoutDuration(Duration.ofSeconds(10))           // 超时时间：10秒
                            .build())
                    .build());
        };
    }
} 